package com.hjm.project.agentInfo.profitSbOrder.utils;

import com.hjm.common.utils.trade.LoFunction;
import com.hjm.framework.config.CustomConfig;
import com.hjm.framework.web.domain.AjaxResult;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class OrderUtils {

    private static LoFunction lo = new LoFunction();

    public static AjaxResult sendOrder(String data) throws Exception {
        String requestData = data;
        byte[] resByte = requestData.getBytes();
        byte[] reqPack = new byte[2 + resByte.length];
        int lenByte = reqPack.length - 2; // 获得报文的长度(不包括2个byte的长度)
        String str = lo.initSize(Integer.toString(lenByte, 16));
        byte[] lenByteHex = lo.hexStr2Bytes(str);
        byte[] reqBody = lo.assemble(lenByteHex, resByte);
        //TODO 分润审核单推送接口(推送订单至分润)
        byte[] resp=connServer(reqBody);
        String pack = lo.byte2HexStr(resp);
        String respStr = lo.hexStr2Str(pack);
        if ("200".equals(respStr)){
               /* orderNumber.put("beForState","4");
                int num = profitSbOrderMapper.auditOrder(orderNumber);*/
            return AjaxResult.success("审核成功");
        }
        return AjaxResult.error("审核失败");
    }

    public static byte[] connServer(byte[] reqPack) throws Exception {
        Socket socket = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            String ipAddress = CustomConfig.getOrderCompleteUrl();
            int port = Integer.parseInt(CustomConfig.getOrderCompletePort());
            socket = new Socket(); // 建立与服务器端的链接
            socket.connect(new InetSocketAddress(ipAddress, port), 60000); // 连接超时设置
            socket.setSoTimeout(60000); // 读写超时设置
            os = socket.getOutputStream();
            is = socket.getInputStream();
            os.write(reqPack);
//			System.out.println("请求包：" + lo.byte2HexStr(reqPack));
            os.flush();
            // 接收服务器的响应
            byte[] lenByte = new byte[2];
            is.read(lenByte, 0, 2);
            int len = (int) lo.byteArrayToShort(lenByte);
            byte[] bb = new byte[len];
            is.read(bb, 0, len);
            byte[] respPack = new byte[lenByte.length + bb.length];
//			System.arraycopy(lenByte, 0, respPack, 0, 2);
//			System.arraycopy(bb, 0, respPack, lenByte.length, bb.length);
            return lo.checkByte(bb) ? null : bb;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (socket != null){
                socket.close();
            }
            if (is != null){
                is.close();
            }
            if (os != null){
                os.close();
            }
        }
    }

}
